package com.stationbuilding.fragment.member;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.stationbuilding.R;
import com.stationbuilding.adapter.member.MemberFragmentPagerAdapter;
import com.stationbuilding.utils.TabLayoutUtil;

import java.util.ArrayList;

public class MemberFragment extends Fragment {

    private View view;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private LinearLayout search;
    private EditText searchEdit;
    private boolean checkModal;
    private String currentTag;
    private MemberFragmentMember memberFragmentMember;
    private MemberFragmentCompany memberFragmentCompany;
    public static final String TAB_MEMBER = "按成员显示";
    public static final String TAB_COMPANY = "按公司显示";

    public MemberFragment(boolean checkModal) {
        this.checkModal = checkModal;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_member, container, false);
        initView();
        initViewPager();
        initSearchView();
        return view;
    }

    private void initView() {
        searchEdit = (EditText) view.findViewById(R.id.search_edit);
        search = (LinearLayout) view.findViewById(R.id.search);
        tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
    }

    private void initViewPager() {
        // 创建一个集合,装填Fragment
        ArrayList<Fragment> fragments = new ArrayList<>();
        // 装填
        memberFragmentMember = new MemberFragmentMember(checkModal);
        memberFragmentCompany = new MemberFragmentCompany(checkModal);
        fragments.add(memberFragmentMember);
        fragments.add(memberFragmentCompany);

        MemberFragmentPagerAdapter memberFragmentPagerAdapter = new MemberFragmentPagerAdapter(getChildFragmentManager(), fragments);
        viewPager.setAdapter(memberFragmentPagerAdapter);
        initTabLayout();
        tabLayout.setupWithViewPager(viewPager);
    }

    /**
     * 初始化页签
     */
    private void initTabLayout() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                InputMethodManager inputMethodManager = (InputMethodManager)searchEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                searchEdit.setVisibility(View.GONE);
                searchEdit.setText("");
                search.setVisibility(View.VISIBLE);
                currentTag = tab.getText().toString();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                TabLayoutUtil.setIndicator(tabLayout, 55, 55);
            }
        });
    }

    /**
     * 初始化搜索图片按钮
     */
    private void initSearchView() {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search.setVisibility(View.GONE);
                searchEdit.setVisibility(View.VISIBLE);
                searchEdit.requestFocus();
                InputMethodManager inputMethodManager = (InputMethodManager)searchEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
            }
        };

        // 根据输入框输入值的改变来过滤搜索
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                if (TAB_MEMBER.equals(currentTag)) {
                    memberFragmentMember.filterData(s.toString());
                } else {
                    memberFragmentCompany.filterData(s.toString());
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        search.setOnClickListener(onClickListener);
    }

//    private void setAdapter() {
//        memberList = filledData(getResources().getStringArray(R.array.contacts));
//        Collections.sort(memberList, new PinyinComparator());
//        memberListAdapter = new MemberListAdapter(getActivity(), memberList, checkModal);
//        listView.setAdapter(memberListAdapter);
//    }
//
//    private void initEvents() {
//        // ListView的点击事件
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (checkModal) {
//                    String userId = ((MemberBean) memberListAdapter.getItem(position)).getId();
//                    if (userIdList.contains(userId)) {
//                        int index = userIdList.indexOf(userId);
//                        userIdList.remove(index);
//                        userNameList.remove(index);
//                        ((MemberBean) memberListAdapter.getItem(position)).setChecked(false);
//                    } else {
//                        userIdList.add(userId);
//                        userNameList.add(((MemberBean) memberListAdapter.getItem(position)).getName());
//                        ((MemberBean) memberListAdapter.getItem(position)).setChecked(true);
//                    }
//                    memberListAdapter.notifyDataSetChanged();
//                } else {
//                    getActivity().startActivity(new Intent(getActivity(), MemberDetailsActivity.class));
//                }
//            }
//        });
//    }
//
//    /**
//     * 根据输入框中的值来过滤数据并更新ListView
//     *
//     * @param filterStr
//     */
//    public void filterData(String filterStr) {
//        List<MemberBean> sortList = new ArrayList<>();
//        if (TextUtils.isEmpty(filterStr)) {
//            sortList = memberList;
//        } else {
//            sortList.clear();
//            for (MemberBean memberBean : memberList) {
//                String name = memberBean.getName();
//                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtil.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
//                    sortList.add(memberBean);
//                }
//            }
//        }
//        // 根据a-z进行排序
//        Collections.sort(sortList, new PinyinComparator());
//        memberListAdapter.updateListView(sortList);
//    }
//
//    private List<MemberBean> filledData(String[] data) {
//        List<MemberBean> sortList = new ArrayList<>();
//        ArrayList<String> indexString = new ArrayList<>();
//
//        for (int i = 0; i < data.length; i++) {
//            MemberBean memberBean = new MemberBean();
//            memberBean.setName(data[i]);
//            memberBean.setId(String.valueOf(i));
//            String pinyin = PinyinUtil.getPingYin(data[i]);
//            String sortString = pinyin.substring(0, 1).toUpperCase();
//            if (sortString.matches("[A-Z]")) {
//                memberBean.setSortLetters(sortString.toUpperCase());
//                if (!indexString.contains(sortString)) {
//                    indexString.add(sortString);
//                }
//            }
//            sortList.add(memberBean);
//        }
//        Collections.sort(indexString);
//        return sortList;
//    }
//
    /**
     * 设置选择结果
     */
    public void setResult() {
        if (TAB_MEMBER.equals(currentTag)) {
            memberFragmentMember.setResult();
        } else {
            memberFragmentCompany.setResult();
        }
    }
}
